package cn.bon.emp.service.impl;


import cn.bon.emp.api.pojo.dto.EmpsDTO;
import cn.bon.emp.api.pojo.po.*;
import cn.bon.emp.api.pojo.vo.EmpInfoVO;
import cn.bon.emp.api.pojo.vo.NotGroupedVO;
import cn.bon.emp.mapper.EmpInfoMapper;
import cn.bon.emp.mapper.UniEmpInfoSkillMapper;
import cn.bon.emp.service.*;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 *
 * @author luochao
 * @since 2023-12-09
 */
@Service
public class EmpInfoServiceImpl extends ServiceImpl<EmpInfoMapper, EmpInfo> implements IEmpInfoService {

    @Resource
    UniEmpInfoSkillMapper uniEmpInfoSkillMapper;
    @Resource
    EmpInfoMapper empInfoMapper;

    @Resource
    IEmpOrgService empOrgService;
    @Resource
    IUniEmpInfoSkillService empInfoSkillService;
    @Resource
    IEmpJobService empJobService;
    @Resource
    IOrgService orgService;

    /**
     * 根据条件分页查询
     * @param dto
     * @param orgId
     * @return
     */
    @Override
    public Page<EmpInfoVO> doPage(EmpsDTO dto, Long orgId) {

        //1.筛选
        LambdaQueryWrapper<EmpInfo> queryWrapper = new LambdaQueryWrapper<>();
        //1.1筛选组织
        List<Long> empIds = orgEmpIds(orgId);
        queryWrapper.in(EmpInfo::getEmpId, empIds);
        //1.2姓名
        queryWrapper.like(StringUtils.isNotBlank(dto.getEmpName()), EmpInfo::getEmpName, dto.getEmpName());
        //1.3岗位
        queryWrapper.eq(dto.getEmpJobId() != null && dto.getEmpJobId() != 0, EmpInfo::getEmpJobId, dto.getEmpJobId());
        //1.4备勤状态
        if (dto.getStatus() < 2) queryWrapper.eq(EmpInfo::getStatus, dto.getStatus());

        //1.5时间
        boolean timeFlag = dto.getStart() != null && dto.getEnd() != null;
        queryWrapper.between(timeFlag, EmpInfo::getUpdateTime, dto.getStart(), dto.getEnd());
        //1.6skill
        List<Long> skills = dto.getSkills();
        if (skills != null && !skills.isEmpty()) {
            List<Long> haveSkillIds  = haveSkillEmpIds(skills);
            if (haveSkillIds.isEmpty()) haveSkillIds.add(Long.MIN_VALUE);//为空则筛选不到
            queryWrapper.in(EmpInfo::getEmpId,haveSkillIds);
        }
        //1.7排序
        queryWrapper.orderByDesc(EmpInfo::getUpdateTime);


        // 创建page对象
        Integer crr = dto.getCurrent();
        Integer pageSize = dto.getPageSize();
        if (crr == null || crr < 1) crr = 1;
        if (pageSize == null || pageSize < 1) pageSize = 10;
        Page<EmpInfo> pageInfo = new Page<>(crr, pageSize);

        //page对象属性复制
        Page<EmpInfo> empInfoPage = this.page(pageInfo, queryWrapper);
        Page<EmpInfoVO> rePage = new Page<>();
        BeanUtils.copyProperties(empInfoPage, rePage, "records");

        //records填充
        List<EmpInfoVO> records = fillVO(empInfoPage.getRecords());
        rePage.setRecords(records);

        return rePage;
    }

    /**
     * 筛选指定组织的员工id
     * @param orgId
     * @return
     */
    private List<Long> orgEmpIds(Long orgId) {
        List<Long> empId = empOrgService.getEmpIdsOf(orgId);


/*        LambdaQueryWrapper<EmpOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmpOrg::getCompanyId, orgId)
                .or().eq(EmpOrg::getDeptId, orgId)
                .or().eq(EmpOrg::getSectionId, orgId)
                .or().eq(EmpOrg::getGroupId, orgId);
        List<Long> empId = empOrgService.list(queryWrapper).stream().map(empOrg -> {
            return empOrg.getEmpId();
        }).collect(Collectors.toList());    //在orgId下属的员工id
        empId.add(Long.MIN_VALUE);*/
        return empId;
    }

    /**
     * 筛选拥有该技能的员工id
     * @param skills
     * @return
     */
    private List<Long> haveSkillEmpIds(List<Long> skills) {
//        LambdaQueryWrapper<UniEmpInfoSkill> queryWrapper = new LambdaQueryWrapper<>();
        List<Long> reEmpIds = null;
        for (Long skillId : skills) {
//            queryWrapper.clear();
            List<Long> collect = uniEmpInfoSkillMapper.getEmpsWith(skillId);

//            queryWrapper.eq(UniEmpInfoSkill::getEmpSkillId, skillId);
//            List<Long> collect = empInfoSkillService.list(queryWrapper)
//                    .stream().map(UniEmpInfoSkill::getEmpId)
//                    .collect(Collectors.toList());

            if (reEmpIds==null) reEmpIds = collect;
            else reEmpIds.retainAll(collect);
        }
        return reEmpIds;
    }

    /**
     * 填充skills;
     * 填充岗位名称
     * 填充用户所属机构Id
     *
     * @param emps
     * @return
     */
    private List<EmpInfoVO> fillVO(List<EmpInfo> emps) {
        if (emps.isEmpty()) return Collections.emptyList();

//        LambdaQueryWrapper<UniEmpInfoSkill> empInfoSkillQW = new LambdaQueryWrapper<>();

        List<EmpInfoVO> reVo = emps.stream().map(empInfo -> {
            EmpInfoVO empInfoVO = new EmpInfoVO();
            BeanUtils.copyProperties(empInfo, empInfoVO);

            //资质技能
            List<UniEmpInfoSkill> skills = empInfoSkillService.getSkillsBy(empInfo.getEmpId());
//            empInfoSkillQW.clear();
//            empInfoSkillQW.eq(UniEmpInfoSkill::getEmpId, empInfo.getEmpId());
//            List<UniEmpInfoSkill> skills = empInfoSkillService.list(empInfoSkillQW);
            empInfoVO.setSkills(skills);

            //工作名称
            EmpJob job = empJobService.getById(empInfo.getEmpJobId());
            if (job!=null) empInfoVO.setJobName(job.getEmpJobName());

            //所属机构
            EmpOrg empOrg = empOrgService.getById(empInfo.getEmpId());
            if (empOrg!=null) {
                empInfoVO.setEmpOrg(empOrg);
                //组别
                Org orgInfo = orgService.getById(empOrg.getGroupId());
                if (orgInfo != null) empInfoVO.setGroupName(orgInfo.getOrgName());
            }

            return empInfoVO;
        }).collect(Collectors.toList());

        return reVo;
    }

    /**
     * 修改备勤状态
     *
     * @param empIds
     * @param status
     */
    @Override
    public void setStatus(Long[] empIds, Integer status) {
//        LambdaUpdateWrapper<EmpInfo> updateWrapper = new LambdaUpdateWrapper<>();

        for (Long empId : empIds) {
            empInfoMapper.setStat(empId, status);
//
//            updateWrapper.clear();
//            updateWrapper.eq(EmpInfo::getEmpId, empId);
//            updateWrapper.set(EmpInfo::getStatus, status);
//            this.update(updateWrapper);
        }
    }

    /**
     * 获取指定部门下未分组的所有员工
     * @param deptId
     * @return
     */
    @Override
    public List<NotGroupedVO> getNotGrouped(Long deptId) {
        //获取所有该部门下的科室
        LambdaQueryWrapper<Org> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Org::getParentId, deptId);
        List<Org> sections = orgService.list(queryWrapper);

        //包装vo
        List<NotGroupedVO> vos = sections.stream().map(section -> {
            NotGroupedVO vo = new NotGroupedVO();
            BeanUtils.copyProperties(section, vo);

            //获取人员Id
            LambdaQueryWrapper<EmpOrg> empOrgWrapper = new LambdaQueryWrapper<>();
            empOrgWrapper.eq(EmpOrg::getSectionId, section.getOrgId())
                    .isNull(EmpOrg::getGroupId);
            List<Long> empIds = empOrgService.list(empOrgWrapper).stream().map(EmpOrg::getEmpId).collect(Collectors.toList());

            //获取人员详情
            LambdaQueryWrapper<EmpInfo> empInfoWrapper = new LambdaQueryWrapper<>();
            empInfoWrapper.in(EmpInfo::getEmpId, empIds);
            List<EmpInfo> empInfos = this.list(empInfoWrapper);

            //注入vo
            vo.setNotGroupedEmps(empInfos);
            return vo;
        }).collect(Collectors.toList());

        return vos;
    }
}
